import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-04-16
 * Time: 15:46
 */
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }
    //前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
//    List<Integer> list = new ArrayList<>();
//    public List<Integer> preorderTraversal(TreeNode root) {
//        if(root == null) {
//            return list;
//        }
//        list.add(root.val);
//        preorderTraversal(root.left);
//        preorderTraversal(root.right);
//        return list;
//    }
//    public List<Integer> preorderTraversal(TreeNode root) {
//        List<Integer> list = new ArrayList<>();
//        if(root == null) {
//            return list;
//        }
//        list.add(root.val);
//        List<Integer> leftlist = preorderTraversal(root.left);
//        list.addAll(leftlist);
//        List<Integer> rightlist = preorderTraversal(root.right);
//        list.addAll(rightlist);
//        return list;
//    }


    //中序遍历
    public void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }
    public List<Integer> inOrderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        List<Integer> leftList = inOrderTraversal(root.left);
        list.addAll(leftList);
        //list.add(root.val);
        List<Integer> rightList = inOrderTraversal(root.right);
        list.addAll(rightList);
        return list;
    }

    //后序遍历
    public void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }
    public List<Integer> postOrderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        List<Integer> leftList = inOrderTraversal(root.left);
        list.addAll(leftList);
        List<Integer> rightList = inOrderTraversal(root.right);
        list.addAll(rightList);
        //list.add(root.val);
        return list;
    }

    public int size(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }
    public int num = 0;
    public int size1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        num++;
        size1(root.left);
        size1(root.right);
        return num;
    }
    public static int leafSize = 0;

    void getLeafNodeCount1(TreeNode root) {
        if(root != null && root.left == null && root.right == null) {
            leafSize++;
            getLeafNodeCount1(root.right);
            getLeafNodeCount1(root.left);
        }
    }
    public int getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
    }
    public int getKLevelNodeCount(int k, TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(k - 1, root.left) + getKLevelNodeCount(k - 1, root.right);
    }
    /**
     *
     * 时间复杂度为On
     * */
    public static int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }
    public TreeNode find(TreeNode root, char val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode findLeft = find(root.left, val);
        if(findLeft != null) {
            return findLeft;
        }
        return find(root.right, val);
    }

    /**
     * 判断两棵树是否相同
     * 时间复杂度为 O(min(m,n))
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q != null || p != null && q == null) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

    }

    /**
     * 判断是不是另一棵树的子树
     * 时间复杂度：s*t
     * 每个root结点都要和subRoot判断是否相同
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) {
            return true;
        }
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);

    }

    /**
     * 反转二叉树
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode ret = root.left;
        root.left = root.right;
        root.right = ret;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    /**
     * 判断平衡二叉树
     * 时间复杂度为O(n^2)
     * @param root
     * @return
     */
    public boolean isBalanced1(TreeNode root) {
        if(root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return Math.abs(leftH - rightH) < 2 && isBalanced1(root.left) && isBalanced1(root.right);
    }

    /**
     * 优化
     * @param root
     * @return
     */
    public static int getHeight1(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = getHeight1(root.left);
        int rightH = getHeight1(root.right);
        if(leftH >= 0 && rightH >= 0 && Math.abs(leftH - rightH) <= 1) {
            return Math.max(leftH, rightH) + 1;
        } else {
            return -1;
        }
    }
    public boolean isBalanced2(TreeNode root) {
        if(root == null) {
            return true;
        }
        return getHeight1(root) >= 0;
    }

    /**
     * 对称二叉树
     * @param root
     * @return
     */

    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isSymmetricChild(root.left,root.right);
    }
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree == null && rightTree == null) {
            return true;
        } else if(leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree.val == rightTree.val) {
            return isSymmetricChild(leftTree.left, rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
        } else {
            return false;
        }
    }

    /**
     * 层序遍历
     * @param root
     */
    public void levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if(root != null) {
            queue.offer(root);
        }
        while(!queue.isEmpty()) {
            TreeNode top = queue.poll();
            System.out.print(top.val + " ");
            if(top.left != null) {
                queue.offer(top.left);
            }
            if(top.right != null) {
                queue.offer(top.right);
            }
        }
    }

//    public List<List<Integer>> levelOrder2(TreeNode root) {
//        List<List<Integer>> listAll = new ArrayList<>();
//        Queue<TreeNode> queue = new LinkedList<>();
//        if(root != null) {
//            queue.offer(root);
//        } else {
//            return listAll;
//        }
//        while(!queue.isEmpty()) {
//            int size = queue.size();
//            List<Integer> list = new ArrayList<>();
//            while(size != 0) {
//                TreeNode top = queue.poll();
//                list.add(top.val);
//                if(top.left != null) {
//                    queue.offer(top.left);
//                }
//                if(top.right != null) {
//                    queue.offer(top.right);
//                }
//                size--;
//            }
//            listAll.add(list);
//            listAll.add(0,list);
//        }
//        return listAll;
//    }

    /**
     * 是否是完全二叉树
     * @param root
     * @return
     */
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                return false;
            }
        }
        return true;
    }


    /**
     * 二叉树的最近公共祖先
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        if(p == root || q == root) {
            return root;
        }
        TreeNode leftRet = lowestCommonAncestor(root.left, p, q);
        TreeNode rightRet = lowestCommonAncestor(root.right, p, q);
        if(leftRet != null && rightRet != null) {
            return root;
        } else if(leftRet != null) {
            return leftRet;
        } else {
            return rightRet;
        }
    }
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root, p, stack1);
        getPath(root, q, stack2);
        int size1 = stack1.size();
        int size2 = stack2.size();

        if(size1 > size2) {
            int size = size1 - size2;
            while (size != 0) {
                stack1.pop();
                size--;
            }
        } else {
            int size = size2 - size1;
            while (size != 0) {
                stack2.pop();
                size--;
            }
        }
        while (!stack1.empty() && !stack2.empty()) {
            TreeNode val1 = stack1.pop();
            TreeNode val2 = stack2.pop();
            if(val1 == val2) {
                return val1;
            }
        }
        return null;
    }

    /**
     * 再root这棵树上，找到node这个节点的位置
     * @param root
     * @param node
     * @return
     */
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if(root == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean ret = getPath(root.left, node, stack);
        if(ret == true) {
            return true;
        }
        boolean ret2 = getPath(root.right, node, stack);
        if (ret2 ==true) {
            return true;
        }
        stack.pop();
        return false;
    }

    /**
     * 前序遍历非递归
     * @param root
     */
    public void preOrder2(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.empty()){
            while(cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            //cur == null
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    /**
     * 中序遍历非递归
     * @param root
     */
    public void inOrder2(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.empty()){
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            //cur == null
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }
    public void postOrder2(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null || !stack.empty()){
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev) {
                System.out.print(top.val + " ");
                prev = top;
                stack.pop();
            } else {
                cur = top.right;
            }
        }
    }
    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root, stringBuilder);
        return stringBuilder.toString();

    }
    private void tree2strChild(TreeNode t, StringBuilder stringBuilder){
        if(t == null) {
            return;
        }
        stringBuilder.append(t.val);
        if(t.left != null) {
            stringBuilder.append("(");
            tree2strChild(t.left, stringBuilder);
            stringBuilder.append(")");

        } else {
            if(t.right == null) {
                return;
            } else {
                stringBuilder.append("()");
            }
        }
        if(t.right != null) {
            stringBuilder.append("(");
            tree2strChild(t.right, stringBuilder);
            stringBuilder.append(")");
        }
    }
}

